#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"
#include "Protocol.hpp"

// ./client_tcp server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: ./client_tcp server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);

    // 1. 创建套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket error" << std::endl;
        return 2;
    }

    // 2. 客户端不需要显示的进行绑定, 但是需要连接服务器, 在建立连接的过程由操作系统进行绑定IP和端口号
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(server_port);
    server.sin_addr.s_addr = ::inet_addr(server_ip.c_str());

    int n = ::connect(sockfd, CONV(&server), sizeof(server));
    if (n < 0)
    {
        std::cout << "connect error" << std::endl;
        return 3;
    }

    std::string message;
    while (true)
    {
        int x, y;
        char oper;
        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;
        Request req(x, y, oper);

        // 1. 序列化
        req.Serialize(message);

        // 2. 添加报头字段
        Encode(message);

        // 3. 向服务器发送报文
        n = ::send(sockfd, message.c_str(), message.size(), 0);
        if (n > 0)
        {
            // 4. 获取服务器响应后的报文
            char inbuffer[1024];
            int m = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (m > 0)
            {
                inbuffer[m] = 0;
                std::string package = inbuffer; // 认为该是报文完整

                // 5. 删除报头字段
                std::string content;
                Decode(package, &content);

                // 6. 反序列化
                Response resp;
                resp.Deserialize(content);

                // 7. 得到结构化数据
                std::cout << resp.Result() << "[" << resp.Code() << "]" << std::endl;
            }
            else break;
        }
        else break;
    }
    ::close(sockfd);

    return 0;
}